﻿using Furion;
using LocalNas.Core.Extension;
using LocalNas.Core.Option;
using LocalNas.Core.SqlSugar;
using LocalNas.Core.Util;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System.Net.Http;
using System.Net.Security;
using Yitter.IdGenerator;

namespace LocalNas.Web.Core
{
    public class Startup : AppStartup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddConsoleFormatter();
            // 配置选项
            services.AddProjectOptions();

            services.AddSqlSugar();

            services.AddJwt<JwtHandler>(enableGlobalAuthorize: true);
            services.AddVirtualFileServer();
            services.AddCorsAccessor();
            services.AddRemoteRequest(options =>
            {
                // 需在所有客户端注册之前注册
                options.ApproveAllCerts();

                // 忽略 SSL 不安全检查，或 https 不安全或 https 证书有误
                options.AddHttpClient(string.Empty)
                       .ConfigurePrimaryHttpMessageHandler(u => new SocketsHttpHandler
                       {
                           AllowAutoRedirect = true,
                           SslOptions = new SslClientAuthenticationOptions
                           {
                               RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true
                           }
                       });
            });


            // 任务调度
            services.AddTaskScheduler();
            // 日志监听
            services.AddMonitorLogging();
            // logo显示
            services.AddLogoDisplay();

            services.AddControllersWithViews()
                .AddAppLocalization()
                .AddNewtonsoftJson(options =>
                {
                    options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); // 首字母小写（驼峰样式）
                    options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss"; // 时间格式化
                    options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; // 忽略循环引用
                                                                                                     // options.SerializerSettings.Converters.Add(new LongJsonConverter()); // long转string（防止js精度溢出） 超过16位开启
                                                                                                     // options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore; // 忽略空值
                })
                .AddInjectWithUnifyResult<AdminResultProvider>();


            // 事件总线
            services.AddEventBus(options =>
            {
                // 不启用事件日志
                options.LogEnabled = false;
                // 事件执行器（失败重试）
                //options.AddExecutor<RetryEventHandlerExecutor>();

            });

            // 即时通讯
            services.AddSignalR();

            // 配置雪花Id算法机器码
            YitIdHelper.SetIdGenerator(new IdGeneratorOptions
            {
                WorkerId = App.GetOptions<SnowIdOptions>().WorkerId
            });
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseSpecificationDocuments("swagger");
            //app.UseHttpsRedirection();

            app.UseRouting();

            app.UseCorsAccessor();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseInject(string.Empty);

            app.UseDefaultFiles();
            app.UseStaticFiles();

            app.UseEndpoints(endpoints =>
            {
                // 注册集线器
                endpoints.MapHubs();
                endpoints.MapControllers();
            });
        }
    }
}